package cn.da.shuai.cool.mq.mqtt.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.*;
import org.springframework.context.annotation.Bean;

@Slf4j
//@Configuration
public class MqttConfigBack {

    @Bean
    public MqttClient mqttClient(MqttProperties mqttProperties) throws MqttException {
        MqttClient mqttClient = new MqttClient(mqttProperties.getHost(), mqttProperties.getClientId());
        mqttClient.setCallback(new Callback());
        mqttClient.connect(mqttProperties.getOptions());
        log.info("Mqtt client init success");
        return mqttClient;
    }

    @Slf4j
    public static class Callback implements MqttCallback {
        @Override
        public void connectionLost(Throwable throwable) {
            log.info("Mqtt client connection lost: {}", throwable.getMessage());
        }

        @Override
        public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
            log.info("Mqtt client message arrived: {}", new String(mqttMessage.getPayload()));
        }

        @Override
        public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
            try {
                log.info("Mqtt client delivery complete: {}", iMqttDeliveryToken.getMessage().toString());
            } catch (MqttException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
